﻿(function($) {
    jQuery.fn.autoList = function(options, data) {

        // 初始化设定
        opts = $.extend({}, jQuery.fn.autoList.defaults, options);
        if (opts.onResult == false)
            alert("please set onResult function in options");
        //initialze priveate data;
        content = this;
        height = parseInt($(this).height());
        $(this).scroll(getdatas).addClass("autoList");      
        $(this).prepend("<div id='autoListLoading'>loading</div>");
        return this;
    };

    jQuery.fn.autoList.defaults = {
        url: false, // ajax get data url    
        dataType: "json", //ajax dataType         
        onScrolling: false,  //当Scrollbar到达接近底部的时候就发送。一旦这个事件被截取,那么其他事件就会失效。
        onSending: false, //before send data to remote service.
        onSendingData: false, //a function, it need to return custom data for sending,
        onResult: false, //on return data ,function(result)      
    };

    jQuery.autoList
    {
        var height = 0;
        var index = -1;
        var loading = false;
        var content;
        var opts;       

        getdatas = function() {
            if (loading || $(this).scrollTop() < (this.scrollHeight - height))
                return;            
            //调整loading界面的位置
            var loadingBar=$("#autoListLoading",this);
            var top = this.scrollHeight-loadingBar.outerHeight();           
            var left=$(this).width()- ($(loadingBar).outerWidth())*3;
            loadingBar.css("top",top).css("left",left).fadeIn("slow");            
            
            loading = true;
            index++;

            if (opts.onScrolling != false) {
                opts.onScrolling();
            }
            else {
                sending();
            }
        }

        sending = function() {
            var sendData = null;
            if (opts.onSendingData != false)
                sendData = opts.onSendingData;
            else
                sendData = null;

            $.ajax({
                dataType: opts.dataType,
                url: opts.url + "?" + $.param({ index: index, data: sendData }),
                success: function(datas) {                    
                    opts.onResult(content,datas);
                    loading = false;
                    $("#autoListLoading",content).fadeOut();
                }
            });
        }
        
    }

})($)